package com.rain.service.impl;

import cn.hutool.core.io.FileUtil;
import com.rain.exception.ErrorCode;
import com.rain.exception.ThrowUtils;
import com.rain.manager.CosManager;
import com.rain.service.ScreenshotService;
import com.rain.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
public class ScreenshotServiceImpl implements ScreenshotService {

    @Resource
    private CosManager cosManager;
    @Override
    public String generateAndUploadScreenshot(String webUrl) {
        if(StringUtils.isBlank(webUrl)){
            log.error("网页地址为空");
            return null;
        }
        String localScreenshotPath  = WebScreenshotUtils.saveWebPageScreenshot(webUrl);
        ThrowUtils.throwIf(localScreenshotPath==null, ErrorCode.PARAMS_ERROR,"生成本地截图错误");
        try {
            String cosUrl=uploadScreenshotToCos(localScreenshotPath);
            return cosUrl;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            cleanupLocalFile(localScreenshotPath);
        }
    }

    /**
     * 清理本地文件
     * @param localScreenshotPath
     */
    private void cleanupLocalFile(String localScreenshotPath) {
        File localFile = new File(localScreenshotPath);
        if (localFile.exists()) {
            String fileParent = localFile.getParent();
            FileUtil.del(fileParent);
            log.info("清理本地文件: {}", fileParent);
        }
    }

    /**
     * 上传截图到cos
     * @param localScreenshotPath
     * @return
     */
    private String uploadScreenshotToCos(String localScreenshotPath) {
        if(localScreenshotPath==null){
            return null;
        }
        File screenshotFile  = new File(localScreenshotPath);
        if (!screenshotFile.exists()) {
            log.error("截图不存在");
            return null;
        }
        String fileName  = UUID.randomUUID().toString().substring(0, 8) + "_compressed.jpg";
        String cosKey=generateScreenshotKey(fileName);
        String cosUrl = cosManager.uploadFile(cosKey, screenshotFile);
        return cosUrl;
    }

    /**
     * 生成截图的对象存储键
     * @param fileName
     * @return
     */
    private String generateScreenshotKey(String fileName) {
        String datePath  = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return String.format("/screenshots/%s/%s", datePath, fileName);
    }
}
